<?php

/**
 * @filename source_class.php 2013-11-11 02:10:56x
 * @author Huming Xu <huming17@126.com>
 * @version 1.0.0
 * @copyright DZF (c) 2013, Huming Xu
 */
if (!defined('IN_SITE')) {
    exit('Access Denied');
}

class user_cart {

    public $info_array = array();
    public $page_array = array();
    public $tree_array = array();
    public static $field_value = array();

    static function &instance() {
        static $object;
        if (empty($object)) {
            $object = new self();
        }
        return $object;
    }

    /*
     * 检测课程是否已存于购物车
     */
    public function isAlreadyCartCmId($user_id = 0, $cm_id = 0){
        if(!$user_id || !$cm_id){
            return false;
        }
        
        $cnt = $this->count('user_cart', " and user_id = '".$user_id."' and cm_id = '".$cm_id."' ");
        if($cnt){
            return true;
        }
        
        return false;
    }
    
    /*
     * 检测是否该课程处于待支付中等待支付
     */
    public function isWaitToBuyCmId($user_id = 0, $cm_id = 0){
        $is_success = false;
        if($user_id && $cm_id){//需要同时传递进来用户id和课程id
            $sql_check = "select count(*) as cnt from ".DB::table('trade_course')." where user_id = '".$user_id."' and cm_id = '".$cm_id."' and tc_flag in (1, 5) and isdelete = 0 ";
            $cnt = @DB::result_first($sql_check);
            
            if($cnt){//说明存在该用户的购买记录
                $is_success = true;
            }
            else{//如果当时没有直接找到，可能是存在当初购买的是一个组合课程，此时需要去查询一下该课程编号对应的组合课程号码，并判断用户是否已经购买了组合课程
                // 该情况下传入的cm_id需要通过 pre_course_group_lesson 关联表获取真实的组合课程cg_id，一个cm_id可能会对应多个cg_id
                $sql_cg = "select cg_id from ".DB::table('course_group_lesson')." where cm_id = '".$cm_id."' ";
                
                $cgIdRes = @DB::fetch_all($sql_cg);
                
                $cgIdArr = [];
                if(!empty($cgIdRes) && is_array($cgIdRes)){
                    foreach ($cgIdRes as $item) {
                        $cgIdArr[$item['cg_id']] = $item['cg_id'];
                    }
                }
                
                if(!empty($cgIdArr) && is_array($cgIdArr)){
                    $sql_res = "select count(*) as cnt "
                            . " from ".DB::table('trade_course')." "
                            . " where user_id = '".$user_id."' and cm_id in ('".implode("', '", $cgIdArr)."') and tc_flag in (1, 5) and isdelete = 0 ";
                    $cnt = @DB::result_first($sql_res);
                    if($cnt){//说明存在该用户的购买记录
                        $is_success = true;
                    }
                }
            }
        }
        
        if($is_success){
            return true;
        }
        
        return false;
    }
    
    /*
     * 检测是否已购买课程
     */
    public function isBuyCmId($user_id = 0, $cm_id = 0){
        $is_success = false;
        if($user_id && $cm_id){//需要同时传递进来用户id和课程id
            $sql_check = "select count(*) as cnt from ".DB::table('trade_course')." where user_id = '".$user_id."' and cm_id = '".$cm_id."' and tc_flag = 2 and isdelete = 0 ";
            $cnt = @DB::result_first($sql_check);
            
            if($cnt){//说明存在该用户的购买记录
                $is_success = true;
            }
            else{//如果当时没有直接找到，可能是存在当初购买的是一个组合课程，此时需要去查询一下该课程编号对应的组合课程号码，并判断用户是否已经购买了组合课程
                // 该情况下传入的cm_id需要通过 pre_course_group_lesson 关联表获取真实的组合课程cg_id，一个cm_id可能会对应多个cg_id
                $sql_cg = "select cg_id from ".DB::table('course_group_lesson')." where cm_id = '".$cm_id."' ";
                
                $cgIdRes = @DB::fetch_all($sql_cg);
                
                $cgIdArr = [];
                if(!empty($cgIdRes) && is_array($cgIdRes)){
                    foreach ($cgIdRes as $item) {
                        $cgIdArr[$item['cg_id']] = $item['cg_id'];
                    }
                }
                
                if(!empty($cgIdArr) && is_array($cgIdArr)){
                    $sql_res = "select count(*) as cnt "
                            . " from ".DB::table('trade_course')." "
                            . " where user_id = '".$user_id."' and cm_id in ('".implode("', '", $cgIdArr)."') and tc_flag = 2 and isdelete = 0 ";
                    $cnt = @DB::result_first($sql_res);
                    if($cnt){//说明存在该用户的购买记录
                        $is_success = true;
                    }
                }
            }
        }
        
        if($is_success){
            return true;
        }
        
        return false;
    }
    
    /*
     * 检测是否存在课程
     */
    public function isHasCmId($cm_id = 0){
        if(!$cm_id){//如果没有传递过来参数的话直接就是没有
            return false;
        }
        
        $detail = $this->one_info('course_main', 'cm_id', $cm_id);
        if(empty($detail)){//找不到对应的课程
            return false;
        }
        
        //判断一下课程是否有效，如果无效则返回false
        if($detail['isdelete']){//isdelete
            return false;
        }
        
        //判断一下课程是否在报名时间范围内，如果不在返回false
        $now = time();
        if($detail['cm_buy_starttime'] && ($detail['cm_buy_starttime'] > $now)){//课程存在开始购买时间 尚未到达开始购买时间
            return false;
        }
        
        if($detail['cm_buy_endtime'] && ($detail['cm_buy_endtime'] < $now)){//课程存在开始购买时间 已超过购买结束时间
            return false;
        }
        
        return true;
    }
    
    /*
     * 	获取一条信息
     */
    public function one_info($table_name, $key_name, $key_id = '') {
        $info = array();
        if ($table_name && $key_name && $key_id) {
            $sql = "SELECT * FROM " . DB::table($table_name) . " WHERE " . $key_name . "='" . $key_id . "' LIMIT 1";
            $info = DB::fetch_first($sql);
        }
        return $info;
    }

    /*
     *  添加信息
     */

    public function add($table_name, $insert_data = array()) {
        $insert_id = '';
        if ($table_name && $insert_data) {
            $insert_id = DB::insert($table_name, $insert_data, true, true);
        }
        return $insert_id;
    }

    /*
     *  编辑信息
     */

    public function edit($table_name, $update_data, $where) {
        //DEBUG 定义返回 消息格式与消息代码编号
        $effect_row = '';
        if ($update_data && $where) {
            $effect_row = DB::update($table_name, $update_data, $where);
        }
        return $effect_row;
    }

    /*
     *  删除信息
     */

    public function delete($table_name, $where,$limit=1) {
        $return = '';
        if ($table_name && $where) {
            $return = DB::delete($table_name, $where, $limit);
            //TODO 逻辑删需要创建isdelete字段 0=未删除 1=已删除
            //DB::update($table_name,array('isdelete'=>1), $table_name, $limit=1);
        }
        return $return;
    }

    /*
     *  列表信息
     *
     * @param $table_name string.
     * @param $page_condition array.
     *
     * @return array
     */

    public function index($table_name, $page_condition) {
        $page_result = array();
        $page = $page_condition['page'];
        $limit = $page_condition['limit'];
        $perpage = $page_condition['perpage'];
        $start = (($page - 1) * $perpage);
        $wheresql = $page_condition['wheresql'];
        $orderby = $page_condition['orderby'];
        $sql_info = "SELECT * FROM " . DB::table($table_name) . " WHERE 1=1 " . $wheresql . " " . $page_condition['orderby'] . " " . DB::limit($start, $limit);
        $sql_info_result = DB::fetch_all($sql_info);
        $sql_total_rows = "SELECT count(*) FROM " . DB::table($table_name) . " WHERE 1=1 " . $wheresql . "";
        $sql_total_rows_result = DB::result_first($sql_total_rows);
        //DEBUG 列表数据返回结构
        $page_result = array(
            'page_now' => $page,
            'total_page' => max(1, ceil($sql_total_rows_result / $perpage)),
            //int 返回结果总数
            'total_rows' => $sql_total_rows_result,
            //array 一页数据数组
            'page_data' => $sql_info_result
        );
        return $page_result;
    }

    /**
     * 接口 AJAX或外部请求检索数据
     *
     * @param $table_name string.
     * @param $page_condition array.
     *
     * @return array
     */
    public function api($table_name, $page_condition) {
        $page_result = array();
        $page = $page_condition['page'];
        $limit = $page_condition['limit'];
        $perpage = $page_condition['perpage'];
        $start = (($page - 1) * $perpage);
        $wheresql = $page_condition['wheresql'];
        $orderby = $page_condition['orderby'];
        $sql_info = "SELECT * FROM " . DB::table($table_name) . " WHERE 1=1 " . $wheresql . " " . $page_condition['orderby'] . " " . DB::limit($start, $limit);
        $sql_info_result = DB::fetch_all($sql_info);
        $sql_total_rows = "SELECT count(*) FROM " . DB::table($table_name) . " WHERE 1=1 " . $wheresql . "";
        $sql_total_rows_result = DB::result_first($sql_total_rows);
        //DEBUG 列表数据返回结构
        $page_result = array(
            //int 返回结果总数
            'total_rows' => $sql_total_rows_result,
            //array 一页数据数组
            'page_data' => $sql_info_result
        );
        return $page_result;
    }
    
    /**
     * 购物车计数
     *
     * @param $table_name string.
     * @param $page_condition array.
     *
     * @return array
     */
    public function count($table_name, $where) {
        $count = 0;
        if($table_name && $where){
            $sql_count = "SELECT count(*) FROM " . DB::table($table_name) . " WHERE 1 = 1 and isdelete = 0 " . $where . "";
            $count = DB::result_first($sql_count);
            if(empty($count)){
                $count=0;  
            }
        }
        return $count;
    }

    /*
     *  获取表字段值
     * @param $table_name string
     * @param $key_name string
     * @param $key_id string/array
     * @param $field_name array
     *
     * @return $field_value array
     */

    protected static function get_field_value_by_id($table_name, $key_name, $key_id, $field_name) {
        if (is_array($key_id) && !empty($key_id)) {
            $key_ids = implode('_', $key_id);
            if (!isset(self::$field_value[$key_ids])) {
                $return = DB::fetch_all('SELECT ' . $key_name . ',' . $field_name . ' FROM ' . DB::table($table_name) . " WHERE " . $key_name . " IN (" . dimplode($key_id) . ")");
                foreach ($return AS $key => $value) {
                    $return_tmp[$value[$key_name]] = $value;
                    unset($return[$key]);
                }
                self::$field_value[$key_ids] = $return_tmp;
                $key_id = $key_ids;
            } else {
                $key_id = $key_ids;
            }
        } else {
            if (!isset(self::$field_value[$key_id])) {
                if (strpos($field_name, ",")) {
                    self::$field_value[$key_id] = DB::fetch_first('SELECT ' . $field_name . ' FROM ' . DB::table($table_name) . " WHERE " . $key_name . "='" . $key_id . "' LIMIT 1");
                } else {
                    self::$field_value[$key_id] = DB::result_first('SELECT ' . $field_name . ' FROM ' . DB::table($table_name) . " WHERE " . $key_name . "='" . $key_id . "' LIMIT 1");
                }
            }
        }
        return self::$field_value[$key_id];
    }

    /*
     * ajax 返回信息
     */

    public function return_json($error, $message, $output = 1) {
        $return_array = array(
            "error" => $error,
            "message" => $message
        );
        if ($output) {
            echo json_ext($return_array);
            die;
        } else {
            return json_ext($return_array);
        }
    }

}

?>